//
//  BAAlbumDetailCellNode.m
//  BabyAlbum
//
//  Created by master on 17/2/15.
//  Copyright © 2017年 master. All rights reserved.
//

#import "BAAlbumDetailCellNode.h"
#import "BAAlbumListLayout.h"
#import "BAImageNode.h"
#import "BAHeaderNode.h"
#import "SuPhotoPicker.h"
#import "TZImagePickerController.h"
@interface BAAlbumDetailCellNode () <ASEditableTextNodeDelegate,ASCollectionDataSource, ASCollectionDelegateFlowLayout, BACollectionViewLayoutDelegate,ASCollectionViewLayoutInspecting,TZImagePickerControllerDelegate>

@property (nonatomic, strong) BAAlbumModel *albumModel;
@property (nonatomic, strong) BAAlbumModel *albumModel_Origin;


@property (nonatomic, strong) NSMutableArray *imageList;

//@property (nonatomic, strong) ASImageNode *imageNode;
//@property (nonatomic, strong) ASTextNode *dateNode;
//@property (nonatomic, strong) ASDisplayNode *lineNode;
//@property (nonatomic, strong) ASTextNode *detailNode;
@property (nonatomic, strong) ASButtonNode *returnButton;
@property (nonatomic, strong) ASButtonNode *editButton;
@property (nonatomic, strong) ASEditableTextNode *titleNode;

@property (nonatomic, strong) ASCollectionNode *collectionNode;

@property (nonatomic, strong) BAHeaderNode *headerNode;


@end

@implementation BAAlbumDetailCellNode


- (instancetype)initWithData:(BAAlbumModel *)model{
    if(self = [super init]) {
        _isEditing = NO;
        self.albumModel = model;
        self.albumModel.desc = [self.albumModel.desc stringByAppendingFormat:@"%d",arc4random()%10000000];
        self.albumModel_Origin = model;
        [self viewInit];
        // 临时解决需要解决多线程造成的数据库崩溃
        dispatch_async(dispatch_get_main_queue(), ^{
            self.imageList = [NSMutableArray arrayWithArray:[self.albumModel fetchImageList]];

        });
    }
    return self;
}

- (ASLayoutSpec *)layoutSpecThatFits:(ASSizeRange)constrainedSize
{
    _collectionNode.style.preferredSize = CGSizeMake(constrainedSize.max.width, kScreenHeight - 64);
    _editButton.style.maxSize = CGSizeMake(30, 22.5);
    _returnButton.style.maxSize = CGSizeMake(30, 22.5);
    _titleNode.style.preferredSize = CGSizeMake(150, 30); // 60

    CGFloat hor_interval = (kScreenWidth - (40*2) - (10 *2) - _titleNode.style.preferredSize.width) / 2;

    ASRelativeLayoutSpec *sepc_return = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionCenter verticalPosition:ASRelativeLayoutSpecPositionCenter sizingOption:ASRelativeLayoutSpecSizingOptionMinimumHeight child:_returnButton];
    ASRelativeLayoutSpec *sepc_edit = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionCenter verticalPosition:ASRelativeLayoutSpecPositionCenter sizingOption:ASRelativeLayoutSpecSizingOptionMinimumHeight child:_editButton];
    ASRelativeLayoutSpec *sepc_title = [ASRelativeLayoutSpec relativePositionLayoutSpecWithHorizontalPosition:ASRelativeLayoutSpecPositionCenter verticalPosition:ASRelativeLayoutSpecPositionCenter sizingOption:ASRelativeLayoutSpecSizingOptionMinimumHeight child:_titleNode];
    ASStackLayoutSpec *stack = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionHorizontal spacing:hor_interval justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsCenter children:@[sepc_return,sepc_title,sepc_edit]];
    
    ASStackLayoutSpec *ver  = [ASStackLayoutSpec stackLayoutSpecWithDirection:ASStackLayoutDirectionVertical spacing:10 justifyContent:ASStackLayoutJustifyContentStart alignItems:ASStackLayoutAlignItemsCenter children:@[stack,_collectionNode]];

    return [ASInsetLayoutSpec insetLayoutSpecWithInsets:UIEdgeInsetsMake(30, 0, 0, 0) child:ver];
}


//- (void)layoutDidFinish {
//    [super layoutDidFinish];
//    [self.collectionNode.view mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.equalTo(self.view).with.offset(64);
//        make.left.equalTo(self.view).with.offset(0);
//        make.right.equalTo(self.view).with.offset(0);
//        make.bottom.equalTo(self.view).with.offset(0);
////        make.height.mas_equalTo(kScreenHeight - 70 - 120);
//    }];
//}

- (void)setIsEditing:(BOOL)isEditing {
    _isEditing = isEditing;
    if(_isEditing) {
        [[XYKeyboardHelper sharedInstance] enableKeyboardHelper];
        [self setUpForDismissKeyboard];
    }else {
        [self.view endEditing:YES];
    }
    [self reloadData];
}

- (void)layout {
    [super layout];
}

- (void)reloadData {
    [self.collectionNode reloadData];
}

- (BOOL)editableTextNode:(ASEditableTextNode *)editableTextNode shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text {
    if(editableTextNode.textView.text.length > 20) {
        return NO ;
    }
    return YES && _isEditing;
}

- (void)didLoad {
    [super didLoad];
    self.titleNode.textView.textAlignment = NSTextAlignmentCenter;
}

- (void)back {
    [self.manager.navigationController popViewControllerAnimated:YES];
}

- (void)save {
    if(self.albumModel.coverImage == nil) {
        [MBProgressHUD showError:@"没有封面"];
        return;
    }
    if(self.albumModel.coverImage == nil) {
        [MBProgressHUD showError:@"没有标题"];
        return;
    }
    
//    self.albumModel.desc = self.de
    
    [BADB updateAlbumDataWithModel:self.albumModel];
    [self back];
    [BAALBUM_DATA reloadData];
}

- (void)viewInit {
    
    self.returnButton = [[ASButtonNode alloc] init];
    [self.returnButton setImage:[UIImage imageNamed:@"return.png"] forState:UIControlStateNormal];
    self.returnButton.imageNode.contentMode = UIViewContentModeScaleAspectFit;
    [self.returnButton addTarget:self action:@selector(back) forControlEvents:ASControlNodeEventTouchUpInside];
    [self addSubnode:self.returnButton];
    
    self.titleNode = [[ASEditableTextNode alloc] init];
    NSAttributedString *string = [NSAttributedString attributedStringWithString:self.albumModel.title fontSize:13 color:RGBWhite(140)];
    self.titleNode.placeholderEnabled = YES;
    self.titleNode.attributedPlaceholderText = [NSAttributedString attributedStringWithString:@"为当前相册添加标题" fontSize:15 color:RGBWhite(180)];
    self.titleNode.attributedText = string;
    self.titleNode.delegate = self;

  
    [self addSubnode:self.titleNode];
    
    self.editButton = [[ASButtonNode alloc] init];
    [self.editButton setImage:[UIImage imageNamed:@"edit_end.png"] forState:UIControlStateNormal];
    self.editButton.imageNode.contentMode = UIViewContentModeScaleAspectFit;
    [self.editButton addTarget:self action:@selector(save) forControlEvents:ASControlNodeEventTouchUpInside];

    [self addSubnode:self.editButton];
    
    

    BAAlbumListLayout *layout = [[BAAlbumListLayout alloc] init];
    layout.numberOfColumns = 2;
//    [self reloadData];

    layout.headerHeight = [BAHeaderNode calculteHeightWithData:self.albumModel];
    
    self.collectionNode = [[ASCollectionNode alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) collectionViewLayout:layout];
    self.collectionNode.dataSource = self;
    self.collectionNode.delegate = self;
    [self addSubnode:self.collectionNode];
    NSLog(@"tttttttt");

    dispatch_async(dispatch_get_main_queue(), ^{
        self.collectionNode.view.showsHorizontalScrollIndicator = NO;
        self.collectionNode.view.showsVerticalScrollIndicator = NO;
        self.collectionNode.view.layoutInspector = self;
        
        self.collectionNode.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        self.collectionNode.backgroundColor = [UIColor whiteColor];

        [_collectionNode registerSupplementaryNodeOfKind:UICollectionElementKindSectionHeader];
        [self.collectionNode setNeedsLayout];
    });
    
}
#pragma mark - ASCollectionView Data Source

- (ASCellNodeBlock)collectionNode:(ASCollectionNode *)collectionNode nodeBlockForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    UIImage *image;
    if(_isEditing && indexPath.row == self.imageList.count) {
        image = [UIImage imageNamed:@"add_btn.png"];
    } else {
        image = self.imageList[indexPath.row];
    }
    return ^{
        return [[BAImageNode alloc] initWithImage:image];
    };
    
}


- (NSInteger)collectionNode:(ASCollectionNode *)collectionNode numberOfItemsInSection:(NSInteger)section
{
    return _isEditing ? self.imageList.count + 1 : self.imageList.count;
}

- (NSInteger)numberOfSectionsInCollectionNode:(ASCollectionNode *)collectionNode
{
    return 1;
}


- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForNodeAtIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout itemSizeAtIndexPath:indexPath]);
}



- (ASSizeRange)collectionView:(ASCollectionView *)collectionView constrainedSizeForSupplementaryNodeOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    BAAlbumListLayout *layout = (BAAlbumListLayout *)[collectionView collectionViewLayout];
    return ASSizeRangeMake(CGSizeZero, [layout headerSizeForSection:indexPath.section]);
}

- (ASScrollDirection)scrollableDirections
{
    return ASScrollDirectionVerticalDirections;
}

/**
 * Asks the inspector for the number of supplementary views for the given kind in the specified section.
 */
- (NSUInteger)collectionView:(ASCollectionView *)collectionView supplementaryNodesOfKind:(NSString *)kind inSection:(NSUInteger)section
{
    return [kind isEqualToString:UICollectionElementKindSectionHeader] ? 10 : 0;
}

- (ASCellNode *)collectionNode:(ASCollectionNode *)collectionNode nodeForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0) {
        
        self.headerNode = [[BAHeaderNode alloc] initWithData:self.albumModel isEdit:_isEditing selectPhotoBlock:^{
            
            if([self.titleNode.textView isFirstResponder]) {
                [self.view endEditing:YES];
                
            }
            TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
            imagePicker.allowCrop = YES;
            [imagePicker setDidFinishPickingVideoHandle:^(UIImage * image, id obj) {
//                if(photos.count) {
                self.albumModel.coverImage = image;//[photos firstObject];
                    [self reloadData];
//                }

            }];
            [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL isSelectOrigin) {
                if(photos.count) {
                    self.albumModel.coverImage = [photos firstObject];
                    [self reloadData];
                }

            }];
             [KEYWINDOW.rootViewController presentViewController:imagePicker animated:YES completion:nil];
        } textChangeBlock:^(NSString *text) {
            self.albumModel.desc = text;
        }];
        return self.headerNode;

    }
    return [[ASCellNode alloc] init];
}


- (CGSize)collectionView:(ASCollectionNode *)collectionNode layout:(UICollectionViewLayout *)collectionViewLayout originalItemSizeAtIndexPath:(NSIndexPath *)indexPath
{
    ASCellNode *cellNode = [collectionNode nodeForItemAtIndexPath:indexPath];
    if ([cellNode isKindOfClass:[BAImageNode class]]) {
        CGSize size =  [(BAImageNode *)cellNode calculatedSize];
        return size;
    }
    return CGSizeMake(120, 120);
}

- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    return nil;
}

- (void)collectionNode:(ASCollectionNode *)collectionNode didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    if(_isEditing && indexPath.row == self.imageList.count) {
        if([self.titleNode.textView isFirstResponder]) {
            [self.view endEditing:YES];

        }
        TZImagePickerController *imagePicker = [[TZImagePickerController alloc] initWithMaxImagesCount:1 delegate:self];
        imagePicker.allowCrop = YES;
        [imagePicker setDidFinishPickingVideoHandle:^(UIImage * image, id obj) {
            //                if(photos.count) {
            self.albumModel.coverImage = image;//[photos firstObject];
            [self reloadData];
            //                }
            
        }];
        [imagePicker setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> * photos, NSArray *assets, BOOL isSelectOrigin) {
            if(photos.count) {
                [self.imageList addObject:[photos firstObject]];
                self.albumModel.imageList = [self.imageList copy];
                [self reloadData];
            }
            
        }];
        [KEYWINDOW.rootViewController presentViewController:imagePicker animated:YES completion:nil];
    }
}


- (void)editableTextNodeDidUpdateText:(ASEditableTextNode *)editableTextNode {
    self.albumModel.title = editableTextNode.textView.text;
}


#pragma show and hide the keyboard
- (void)setUpForDismissKeyboard {
    NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
    UITapGestureRecognizer *singleTapGR =
    [[UITapGestureRecognizer alloc] initWithTarget:self
                                            action:@selector(tapAnywhereToDismissKeyboard:)];
    NSOperationQueue *mainQuene =[NSOperationQueue mainQueue];
    [nc addObserverForName:UIKeyboardWillShowNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view addGestureRecognizer:singleTapGR];
                }];
    [nc addObserverForName:UIKeyboardWillHideNotification
                    object:nil
                     queue:mainQuene
                usingBlock:^(NSNotification *note){
                    [self.view removeGestureRecognizer:singleTapGR];
                }];
}

- (void)tapAnywhereToDismissKeyboard:(UIGestureRecognizer *)gestureRecognizer {
    //此method会将self.view里所有的subview的first responder都resign掉
    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    [self.view endEditing:YES];
}

@end
